package com.zhen.servlet;

import com.zhen.utils.JdbcUtils;
import org.apache.commons.lang3.RandomStringUtils;

import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.Part;
import java.io.IOException;

@MultipartConfig(location = "D:\\work\\gitee\\test03\\upload-images",maxFileSize = 100*1024*1024,maxRequestSize = 100*1024*1024)
public class GoodsSaveServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("utf-8");
        String name = req.getParameter("n");//名称
        String price = req.getParameter("p");//单价
        Part img = req.getPart("i");//图片文件

        String fileName = img.getSubmittedFileName();//原始图片名称
        String[] split = fileName.split("\\.");
        String s = split[1];
        String newname = RandomStringUtils.randomAlphabetic(10) + "." + s;
        img.write(newname);
        String sql = "insert into `goods` (`name`,`price`,`image`) values (?,?,?)";
        JdbcUtils.modify(sql,name,price,newname);
        resp.sendRedirect("/zhen/goods-list.jsp");
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req, resp);
    }
}
